package com.wayz.service;

import com.wayz.entity.pojo.company.DDepartmentExt;
import com.wayz.entity.redis.company.RDepartment;
import com.wayz.exception.WayzException;
import com.wayz.mapper.DDepartmentDAO;
import com.wayz.redis.RCompanyObject;
import com.wayz.redis.RDepartmentObject;
import com.wayz.util.TimeHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import javax.annotation.Resource;

/**
 * 部分服务接口实现类类
 * 
 * @Author: LGQ
 * @Date: 2020/10/21
 */
@Service(version = "1.0.0", protocol = "dubbo")
@org.springframework.stereotype.Service("departmentService")
@RefreshScope
public class DepartmentServiceImpl implements DepartmentService {
	/** 标识相关 */
	@Resource(name = "rDepartmentObject")
	private RDepartmentObject rDepartmentObject = null;

	/** 标识相关 */
	@Resource(name = "rCompanyObject")
	private RCompanyObject rCompanyObject = null;

	/** DAO相关 */
	/** 部门DAO */
	@Resource(name = "dDepartmentDAO")
	private DDepartmentDAO dDepartmentDAO = null;

	/**
	 * 创建部门
	 *
	 * @param myId
	 * @param companyId 公司标示
	 * @param name 部门名称
	 * @param parentId 部门父级标示
	 * @param haveGroup 是否存在设备组
	 */
	@Override
	public Long createDepartment(Long myId, Long companyId, String name, Long parentId) throws WayzException {
		// 初始化
		String path = "0/";
		Long departId = 0L;
		// 用户创建部门
		if (parentId != -1L) {
			RDepartment rParentDepartment = rDepartmentObject.get(companyId, parentId);
			// 校验父部门标识是否存在
			if (rParentDepartment == null || StringUtils.isEmpty(rParentDepartment.getPath())) {
				throw new WayzException("该父部门不存在!");
			}
			path = rParentDepartment.getPath();
			departId = rCompanyObject.getNewDepartId(companyId);
			path = path + departId.toString() + "/";
		}
		// 组装节点路径
		DDepartmentExt dDepartmentExt = new DDepartmentExt();
		dDepartmentExt.setName(name);
		dDepartmentExt.setParentId(parentId);
		dDepartmentExt.setPath(path);
		dDepartmentExt.setCreatedTime(TimeHelper.getCurrentTimestamp());
		dDepartmentDAO.create(companyId, departId, dDepartmentExt);

		// 维护缓存
		RDepartment rDepartment = new RDepartment();
		rDepartment.setName(name);
		rDepartment.setParentId(parentId);
		rDepartment.setPath(path);
		rDepartmentObject.set(companyId, departId, rDepartment);

		return departId;
	}
}